package exporter

import (
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

// CustomCollector 实现 prometheus.Collector 接口
type CustomCollector struct {
	mu sync.Mutex // 保护并发访问

	// 指标描述符
	cpuDesc *prometheus.Desc
	memDesc *prometheus.Desc
	//hdFailuresDesc     *prometheus.Desc
	//randomValueDesc    *prometheus.Desc
	//requestStatsDesc   *prometheus.Desc
	goroutinesDesc     *prometheus.Desc
	lastScrapeTimeDesc *prometheus.Desc

	// 内部状态
	//hdFailureCounts map[string]float64
	//requestStats    map[string]int
	lastScrapeTime time.Time
	numLimit       int
}

// NewCustomCollector 创建并初始化自定义 Collector
func NewCustomCollector(numLimit int) *CustomCollector {
	return &CustomCollector{
		cpuDesc: prometheus.NewDesc(
			"cpu_top",
			"Current Top N CPU Item",
			[]string{"pid", "cmd"}, // 标签
			nil,                    // 常量标签
		),
		memDesc: prometheus.NewDesc(
			"mem_top",
			"Current Top Mem N Item",
			[]string{"pid", "cmd"}, // 标签
			nil,                    // 常量标签
		),
		//hdFailuresDesc: prometheus.NewDesc(
		//	"hd_errors_total",
		//	"Number of hard-disk errors",
		//	[]string{"device", "type"},             // 标签
		//	prometheus.Labels{"monitor": "custom"}, // 常量标签
		//),
		//randomValueDesc: prometheus.NewDesc(
		//	"random_value",
		//	"Randomly generated value",
		//	nil, nil,
		//),
		//requestStatsDesc: prometheus.NewDesc(
		//	"http_requests_stats",
		//	"Statistics of HTTP requests",
		//	[]string{"method", "status"}, // 标签
		//	nil,
		//),
		goroutinesDesc: prometheus.NewDesc(
			"goroutines_count",
			"Current number of goroutines",
			nil, nil,
		),
		lastScrapeTimeDesc: prometheus.NewDesc(
			"last_scrape_timestamp_seconds",
			"Unix timestamp of the last scrape",
			nil, nil,
		),
		//hdFailureCounts: make(map[string]float64),
		//requestStats:    make(map[string]int),
		lastScrapeTime: time.Now(),
		numLimit:       numLimit,
	}
}

// Describe 实现 Collector 接口的 Describe 方法
func (c *CustomCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- c.cpuDesc
	ch <- c.memDesc
	//ch <- c.hdFailuresDesc
	//ch <- c.randomValueDesc
	//ch <- c.requestStatsDesc
	ch <- c.goroutinesDesc
	ch <- c.lastScrapeTimeDesc
}

// Collect 实现 Collector 接口的 Collect 方法
func (c *CustomCollector) Collect(ch chan<- prometheus.Metric) {
	c.mu.Lock()
	defer c.mu.Unlock()

	// 更新内部状态
	c.updateMetrics()

	//// 模拟CPU温度指标 (每个核心不同温度)
	//for i := 0; i < 4; i++ {
	//	ch <- prometheus.MustNewConstMetric(
	//		c.cpuTempDesc,
	//		prometheus.GaugeValue,
	//		50.0+rand.Float64()*20.0,  // 50-70度之间的随机值
	//		fmt.Sprintf("core-%d", i), // 标签值
	//	)
	//}
	memStr := MemGet(10)
	c.updateMemMetric(memStr, ch)

	cpuStr := CpuGet(10)
	c.updateCpuMetric(cpuStr, ch)

	//// 模拟硬盘错误指标
	//for device, count := range c.hdFailureCounts {
	//	ch <- prometheus.MustNewConstMetric(
	//		c.hdFailuresDesc,
	//		prometheus.CounterValue,
	//		count,
	//		device, "read", // 标签值
	//	)
	//}

	//// 随机值指标
	//ch <- prometheus.MustNewConstMetric(
	//	c.randomValueDesc,
	//	prometheus.GaugeValue,
	//	rand.Float64()*100,
	//)

	//// HTTP请求统计指标
	//for key, count := range c.requestStats {
	//	// key格式: method_status (如 "GET_200")
	//	method := key[:3]
	//	status := key[4:]
	//	ch <- prometheus.MustNewConstMetric(
	//		c.requestStatsDesc,
	//		prometheus.CounterValue,
	//		float64(count),
	//		method, status,
	//	)
	//}

	// Goroutine数量指标
	ch <- prometheus.MustNewConstMetric(
		c.goroutinesDesc,
		prometheus.GaugeValue,
		float64(runtime.NumGoroutine()),
	)

	// 上次采集时间指标
	ch <- prometheus.MustNewConstMetric(
		c.lastScrapeTimeDesc,
		prometheus.GaugeValue,
		float64(c.lastScrapeTime.Unix()),
	)

	// 更新最后采集时间
	c.lastScrapeTime = time.Now()
}

// updateMetrics 更新内部指标状态
func (c *CustomCollector) updateMetrics() {
	//// 模拟硬盘错误数据
	//devices := []string{"/dev/sda", "/dev/sdb", "/dev/nvme0"}
	//for _, dev := range devices {
	//	if rand.Float64() > 0.7 { // 30%概率增加错误计数
	//		c.hdFailureCounts[dev] += 1
	//	}
	//}

	//// 模拟HTTP请求统计数据
	//methods := []string{"GET", "POST", "PUT", "DELETE"}
	//statuses := []string{"200", "404", "500"}
	//for _, method := range methods {
	//	for _, status := range statuses {
	//		key := fmt.Sprintf("%s_%s", method, status)
	//		c.requestStats[key] += rand.Intn(5) // 随机增加0-4
	//	}
	//}
}

//// RecordRequest 记录HTTP请求 (供外部调用)
//func (c *CustomCollector) RecordRequest(method, status string) {
//	c.mu.Lock()
//	defer c.mu.Unlock()
//
//	key := fmt.Sprintf("%s_%s", method, status)
//	c.requestStats[key]++
//}

func (c *CustomCollector) updateMemMetric(memstr string, ch chan<- prometheus.Metric) {
	lines := strings.Split(memstr, "\n")

	processSection := false
	for _, line := range lines {
		if strings.TrimSpace(line) == "" {
			continue
		}
		if strings.Contains(line, "  PID") {
			processSection = true
			continue
		}
		if processSection {
			fields := strings.Fields(line)
			if len(fields) >= 10 {
				pid := fields[0]
				//cpu, _ := strconv.ParseFloat(fields[8], 64)
				//mem, _ := strconv.ParseFloat(fields[5], 64)
                                mem, _ := ParseMemorySize(fields[5])
				cmd := strings.Join(fields[11:], " ")
				ch <- prometheus.MustNewConstMetric(
					c.memDesc,
					prometheus.GaugeValue,
					mem,
					pid, cmd,
				)
			}
		}
	}
}

func (c *CustomCollector) updateCpuMetric(cpustr string, ch chan<- prometheus.Metric) {
	lines := strings.Split(cpustr, "\n")

	processSection := false
	for _, line := range lines {
		if strings.TrimSpace(line) == "" {
			continue
		}
		if strings.Contains(line, "  PID") {
			processSection = true
			continue
		}
		if processSection {
			fields := strings.Fields(line)
			if len(fields) >= 10 {
				pid := fields[0]
				cpu, _ := strconv.ParseFloat(fields[8], 64)
				//mem, _ := strconv.ParseFloat(fields[9], 64)
				cmd := strings.Join(fields[11:], " ")
				ch <- prometheus.MustNewConstMetric(
					c.cpuDesc,
					prometheus.GaugeValue,
					cpu,
					pid, cmd,
				)
			}
		}
	}
}
